# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.

import os

from ksai.config import STATIC_FOLDER_NAME, STORAGE_FOLDER_NAME, MODELS_FOLDER_NAME, LOGS_FOLDER_NAME

PROJECT_ROOT_PATH = os.getenv('PROJECT_ROOT_PATH')


def to_path(s: str, k: int = 6) -> str:
    return "/".join([s[i:i + k] for i in range(0, len(s), k)])


def cleanup(filepath: str) -> str:
    if filepath:
        return (filepath
                .replace('\\', '/')
                .replace('//', '/')
                .replace('..', ''))
    return filepath


def get_parent_filepath(filepath: str = None) -> str:
    return os.path.abspath(os.path.dirname(cleanup(filepath)))


def get_project_root_path(filepath: str = None) -> str:
    global PROJECT_ROOT_PATH
    if PROJECT_ROOT_PATH is None:
        PROJECT_ROOT_PATH = os.path.abspath(
            os.path.join(
                os.path.dirname(os.path.realpath(__file__)),
                os.pardir,
                os.pardir,
            )
        )
    if filepath:
        return os.path.join(PROJECT_ROOT_PATH, cleanup(filepath))
    return PROJECT_ROOT_PATH


def get_project_static_path() -> str:
    return get_project_root_path(STATIC_FOLDER_NAME)


def get_project_models_path() -> str:
    return get_project_root_path(MODELS_FOLDER_NAME)


def get_project_logs_path() -> str:
    return get_project_root_path(LOGS_FOLDER_NAME)


def get_project_storage_path(filepath: str = None) -> str:
    storage_path = get_project_root_path(STORAGE_FOLDER_NAME)
    if filepath:
        return os.path.abspath(os.path.join(storage_path, cleanup(filepath).lstrip('/')))
    return storage_path
